package com.zhike.api.aspect;

import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import lombok.extern.slf4j.Slf4j;

@Aspect
@Component
@Slf4j
public class RequestCountAspect {
    // 原子整数，用于安全地记录并发请求数
    private static final AtomicInteger concurrentRequests = new AtomicInteger(0);

    // 在请求处理方法执行前执行，增加并发请求计数
    @Before("execution(* com.zhike.api.controller.*.*.*(..))")
    public void beforeRequest(JoinPoint joinPoint) {
        concurrentRequests.incrementAndGet();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            // 获取请求方法（如 GET、POST 等）
            String method = request.getMethod();
            // 获取请求路径
            String path = request.getRequestURI();

            log.debug("[{}] {} 请求开始，当前并发请求数: {}", method, path, concurrentRequests.get());
        }

    }

    // 在请求处理方法执行后执行，减少并发请求计数
    @After("execution(* com.zhike.api.controller.*.*.*(..))")
    public void afterRequest(JoinPoint joinPoint) {
        concurrentRequests.decrementAndGet();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            // 获取请求方法（如 GET、POST 等）
            String method = request.getMethod();
            // 获取请求路径
            String path = request.getRequestURI();

            log.debug("[{}] {} 请求结束，当前并发请求数: {}", method, path, concurrentRequests.get());
        }

    }

    // 获取当前的并发请求数
    public static int getConcurrentRequestCount() {
        return concurrentRequests.get();
    }
}
